<?php

namespace think\auth\model;

use think\Collection;
use think\Model;
use think\db\exception\DbException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;

/**
 * 角色.
 */
class RoleModel extends Model
{
    public function __construct($data = [])
    {
        $this->name = config('auth.role.table');
        parent::__construct($data);
    }

    /**
     * 角色改名
     * @param string $name
     * @return bool
     */
    public function Rename(string $name): bool
    {
        return $this->save(['name'=>$name]);
    }

    /**
     * 获取角色下所有权限.
     * @return Collection|array
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function Permissions(): Collection|array
    {
        return PermissionModel::whereIn('id', $this->permission)->select();
    }

    /**
     * 获取角色下所有用户.
     * @return Collection|array
     */
    public function Users(): Collection|array
    {
        return UserModel::where('role', $this->id)->select();
    }

    /**
     * 为当前角色分配一个权限.
     * @param PermissionModel $permission
     * @return bool
     */
    public function AssignPermission(PermissionModel $permission): bool
    {
        $permissionList = explode(',',$this->permission);
        if(!in_array($permission->id, $permissionList)) {
            array_push($permissionList, $permission->id);
            return $this->save(['permission'=>implode(',',$permissionList)]);
        }
        return true;
    }

    /**
     * 为当前角色移除一个权限.
     * @param PermissionModel $permission
     * @return bool
     */
    public function RemovePermission(PermissionModel $permission): bool
    {
        $permissionList = explode(',',$this->permission);
        if(in_array($permission->id, $permissionList)) {
            $permissionList = array_diff($permissionList,[$permission->id]);
            return $this->save(['permission'=>implode(',',$permissionList)]);
        }
        return true;
    }

    /**
     * 为当前角色移除所有权限.
     * @return int
     */
    public function RemoveAllPermission(): int
    {
        return $this->save(['permission'=>'null']);
    }

    /**
     * 通过名称查找角色
     * @param string $name
     * @return RoleModel|null
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public static function FindByName(string $name): RoleModel|null
    {
        return self::where(['name' => $name])->find();
    }

    /**
     * 通过ID查找角色
     * @param int|string $roleId
     * @return RoleModel|null
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public static function FindById(int|string $roleId): RoleModel|null
    {
        return self::where([config('auth.role.primaryKey') => $roleId])->find();
    }
}
